/**
 * @author Erik
 */

/* OVERVIEW:
 * This is the main activity of our application.
 * This activity provides detail view for smaller devices and two-pane
 * view for larger (sw600dp) devices.
 * 
 * IMPLEMENTATION:
 * On smaller devices it hosts ManagerFragment ( list of Managers )
 * On larger devices it hosts both ManagerFragment ( list of Managers ) on 
 * left and AgentFragment - detail of selected agent - on the right. To  enable
 * updates in real time between these fragments on two-pane both of the 
 * fragments define Callback methods implemented in this Activity.   
 */

package sk.stuba.fei.ut.snmpmanager;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class ManagerActivity extends SingleFragmentActivity implements
		AgentFragment.Callbacks, ManagerFragment.Callbacks
{

	@Override
	protected Fragment createFragment()
	{
		return new ManagerFragment();
	}

	/*
	 * activity_masterdetail is defined in refs.xml, and is dependent on device,
	 * on tablet it is activity_twopane.xml on small device it is
	 * activity_manager.xml
	 */
	@Override
	protected int getLayoutId()
	{
		return R.layout.activity_masterdetail;
	}

	/*
	 * On small device fetch AgentPagerActivity On tablet update second pane
	 * implementation of ManagerFragment interface
	 */
	public void onAgentSelected( Agent agent )
	{
		// if detail is not set then we are on small device
		if ( findViewById( R.id.detailFragmentContainer ) == null )
		{
			// start AgentPagerActivity
			Intent i = new Intent( this, AgentPagerActivity.class );
			i.putExtra( AgentFragment.EXTRA_AGENT_ID, agent.getID() );
			startActivity( i );
		}
		else
		{
			FragmentManager fm = getSupportFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();

			Fragment oldDetail = fm
					.findFragmentById( R.id.detailFragmentContainer );
			Fragment newDetail = AgentFragment.newInstance( agent.getID() );

			if ( oldDetail != null ) ft.remove( oldDetail );
			
			ft.add( R.id.detailFragmentContainer, newDetail );
			ft.commit();
		}

	}

	/*
	 * When Agent in detail is updated then we must update the list
	 * implementation of AgentFragment interface
	 */
	public void onAgentUpdated( Agent agent )
	{
		FragmentManager fm = getSupportFragmentManager();
		ManagerFragment listFragment = ( ManagerFragment )
				fm.findFragmentById( R.id.fragmentContainer );
		listFragment.update();
	}

}
